<?php

class User_model extends CI_Model {

    function __construct() {
        parent::__construct();
    }

    /**
     * Add login time to user
     * @param type $id Id of user
     */
    function addUser_login_time($id) {
        $this->db->where('id', $id);
        $this->db->update('users', array('login' => REQUEST_TIME));
    }

    /**
     * Add update time of user infor
     * @param type $id Id of user
     */
    function addUser_update_time($id) {
        $this->db->where('id', $id);
        $this->db->update('users', array('update' => REQUEST_TIME));
    }

    /**
     * Add new user
     * @param type $arr array information of user to add
     * @return type 
     */
    function addUser($arr) {
        $data = array(
            'user' => $arr['user'],
            'pass' => md5($arr['pass']),
            'f_name' => $arr['f_name'],
            'l_name' => $arr['l_name'],
            'status' => 1,
            'role' => $arr['role'],
            'created' => REQUEST_TIME,
            'email' => $arr['email'],
            'login' => 0
        );
        $this->db->insert('users', $data);
        return $this->db->insert_id();
    }

    /**
     * 	Edit user infor
     * @param type $arr array information of user to edit
     * @return type 
     */
    function editUser($arr) {
        $data = array(
            'f_name' => $arr['f_name'],
            'l_name' => $arr['l_name'],
            'role' => $arr['role'],
            'email' => $arr['email']
        );

        if (isset($arr['pass']))
            $data['pass'] = md5($arr['pass']);

        $this->db->where('id', $arr['id']);
        $this->db->where('user', $arr['user']);
        $result = $this->db->update('users', $data);
        $this->addUser_update_time($arr['id']);
        return $result;
    }

    /**
     * Get all user
     * @return type 
     */
    function getUser_all() {
        $query = $this->db->get('users');

        $arr = array();
        foreach ($query->result() as $row) {
            $arr[] = $row;
        }
        return $arr;
    }

    /**
     * Get user infor by user id
     * @param type $uid id of user
     * @return type 
     */
    function getUser_by_id($uid) {
        $query = $this->db->get_where('users', array('id' => $uid));

        $user = null;
        foreach ($query->result() as $row)
            $user = $row;
        return $user;
    }

    /**
     * Remove a user out of database
     * @param type $uid id of user
     * @return type 
     */
    function removeUser($uid) {
        return $this->db->delete('users', array('id' => $uid));
    }

    function editUserStatus($uid, $status) {
        $this->db->where('id', $uid);
        $result = $this->db->update('users', array('status' => $status));
        $this->addUser_update_time($uid);
        return $result;
    }

    /**
     * Validate user infor before add to DB 
     * @param type $arr array data of user 
     * @return type 
     */
    function addUser_validate($arr) {
        extract($arr);

        $err = 0;
        $msg = array();
        // validate username
        if (!$this->validateUsername($username)) {
            $err = -1;
            $msg['username'] = 'Username invalid';
        }
        // validate password
        if (!$this->validatePassword($password)) {
            $msg['password'] = 'Password invalid';
            $err = -1;
        }
        // validate email
        if (!$this->validateEmail($email)) {
            $msg['email'] = 'Email invalid';
            $err = -1;
        }
        //check user exit
        if ($this->checkUserExist($username)) {
            $msg['username'] = 'Username exist';
            $err = -2;
        }
        //check email exit
        if ($this->checkEmailExist($email)) {
            $msg['email'] = 'Email exist';
            $err = -3;
        }

        return array('err' => $err, 'msg' => $msg);
    }

    /**
     * Validate user infor before edit
     * @param type $arr array data of user
     * @return type 
     */
    function editUser_validate($arr) {
        extract($arr);

        $err = 0;
        $msg = array();
        // validate email
        if (!$this->validateEmail($email)) {
            $msg['email'] = 'Email invalid';
            $err = -1;
        }
        //check email exit
        if ($this->checkEmailExist($email, $id)) {
            $msg['email'] = 'Email exist';
            $err = -3;
        }

        if ($newpassword != '') {
            if ($oldpassword == '') {
                $msg['oldpassword'] = 'Please enter your old password.';
                $err = -1;
            } else if (!$this->checkPassword($id, $username, $oldpassword)) {
                $msg['oldpassword'] = 'Your old password incorrect.';
                $err = -4;
            } else if (!$this->validatePassword($newpassword)) {
                $msg['newpassword'] = 'New password invalid.';
                $err = -1;
            }
        }

        return array('err' => $err, 'msg' => $msg);
    }

    private function validateUsername($username) {
        return preg_match('/^[a-zA-Z0-9._-]{3,16}$/i', $username);
    }

    private function validatePassword($password) {
        return preg_match('/^[A-Za-z0-9!@#$%^&*()_]{3,16}$/i', $password);
    }

    private function validateEmail($email) {
        return preg_match('/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/i', $email);
    }

    private function checkUserExist($username) {
        $query_u = $this->db->get_where('users', array('user' => $username));
        return $query_u->num_rows > 0;
    }

    private function checkEmailExist($email, $uid = 0) {
        if ($uid != 0) {
            $query_m = $this->db->get_where('users', array('email' => $email, 'id !=' => $uid));
        } else
            $query_m = $this->db->get_where('users', array('email' => $email));
        return $query_m->num_rows > 0;
    }

    private function checkPassword($uid, $user, $password) {
        $this->db->where('id', $uid);
        $this->db->where('user', $user);
        $this->db->where('pass', do_hash($password, 'md5'));
        // Run the query
        $query = $this->db->get('users');
        // Let's check if there are any results
        return $query->num_rows == 1;
    }

}

?>
